package com.huc.ribbon.rest.rule;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import com.netflix.niws.loadbalancer.DiscoveryEnabledServer;

/**
 * Copyright: Copyright (c) 2019 Hu-Cheng
 *
 * @ClassName: ClientRule.java
 * @Description: 服务负载均衡
 *
 * @version: v1.0.0
 * @author: hucheng
 * @date: Nov 19, 2019 1:36:09 PM
 *
 */
public class ClientRule extends AbstractLoadBalancerRule {

	private Random random = new Random();

	@Override
	public Server choose(Object key) {
		return this.choose(this.getLoadBalancer(), key);
	}

	public Server choose(ILoadBalancer lb, Object key) {
		if (lb == null) {
			return null;
		} else {
			List<Server> allServers = null;
			while (true) {
				allServers = lb.getAllServers();
				Map<Server, Integer> serverMap = new HashMap<Server, Integer>();
				int totalWeight = 0;
				for (Server server : allServers) {
					DiscoveryEnabledServer _server = (DiscoveryEnabledServer) server;
					Map<String, String> matadateMap = _server.getInstanceInfo().getMetadata();
					try {
						Integer weight = Integer.parseInt(matadateMap.get("weight"));
						serverMap.put(_server, weight);
						totalWeight += weight;
					} catch (Exception e) {
						e.printStackTrace();
						System.out.println("[负载均衡权重异常 -- 服务]" + _server.getId());
					}
				}

				if (totalWeight == 0) {
					return null;
				}

				// 获取一个总权重的随机数
				int index = random.nextInt(totalWeight);
				int current = 0;
				for (Map.Entry<Server, Integer> entry : serverMap.entrySet()) {
					current += entry.getValue();
					if (index <= current) {
						return entry.getKey();
					}
				}
				return null;
			}
		}
	}

	@Override
	public void initWithNiwsConfig(IClientConfig clientConfig) {

	}

}
